package com.wp.text;

import com.wp.dao.AccountDao;
import com.wp.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author 卫鹏
 * @Description
 * @createTime 2021年10月20日 13:22:00
 */
public class MybatisTest {

    /**
     * 测试 Mybatis的查询Account所有数据
     */
    @Test
    public void testFindAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建工厂:
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //创建SqlSession对象:
        SqlSession sqlSession = factory.openSession();
        //获取代理对象:
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        //调用查询的方法:
        List<Account> lists = accountDao.findAll();
        for (Account list : lists) {
            System.out.println(list);
        }
        //资源关闭:
        sqlSession.close();
        is.close();
    }

    /**
     * 测试 插入Account表的数据
     */
    @Test
    public void testSaveAccount() throws IOException {
        //加载配置文件:
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建工厂:
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //创建SqlSession对象:
        SqlSession sqlSession = factory.openSession();
        //获取代理对象:
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        //创建Account对象:
        Account account = new Account();
        account.setName("卫鹏");
        account.setMoney(1000.0);
        //调用保存的方法:
        accountDao.saveAccount(account);
        // 提交事务
        sqlSession.commit();
        //资源关闭:
        sqlSession.close();
        is.close();
    }
}
